<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use Prettus\Validator\Contracts\ValidatorInterface;
use Prettus\Validator\Exceptions\ValidatorException;
use App\Http\Requests\RatingSubitemCreateRequest;
use App\Http\Requests\RatingSubitemUpdateRequest;
use App\Models\RatingSubitem;
use App\Repositories\RatingSubitemRepository;
use App\Validators\RatingSubitemValidator;
use App\Presenters\RatingSubitemPresenter;
use App\Models\RatingCategory;

/**
 * Class RatingSubitemsController.
 *
 * @package namespace App\Http\Controllers;
 */
class RatingSubitemsController extends Controller
{
    /**
     * @var RatingSubitemRepository
     */
    protected $repository;

    /**
     * @var RatingSubitemValidator
     */
    protected $validator;

    /**
     * RatingSubitemsController constructor.
     *
     * @param RatingSubitemRepository $repository
     * @param RatingSubitemValidator $validator
     */
    public function __construct(RatingSubitemRepository $repository, RatingSubitemValidator $validator)
    {
        $this->repository = $repository;
        $this->validator  = $validator;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $this->repository->pushCriteria(app('Prettus\Repository\Criteria\RequestCriteria'));
        //$this->repository->setPresenter(RatingSubitemPresenter::class);
        $ratingSubitems = $this->repository->with('ratingCategory')->all();

        if (request()->wantsJson()) {

            return response()->json([
                'data' => $ratingSubitems,
            ]);
        }

        return view('ratingSubitems.index', compact('ratingSubitems'));
    }

    public function create()
    {
        $categories = RatingCategory::all()->pluck('category_name', 'id');
        return view('ratingSubitems.create', compact('categories'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  RatingSubitemCreateRequest $request
     *
     * @return \Illuminate\Http\Response
     *
     * @throws \Prettus\Validator\Exceptions\ValidatorException
     */
    public function store(RatingSubitemCreateRequest $request)
    {
        try {

            $this->validator->with($request->all())->passesOrFail(ValidatorInterface::RULE_CREATE);

            $ratingSubitem = $this->repository->create($request->all());
            $totalScore = $this->repository->where('category_id', $ratingSubitem->category_id)->sum('subitem_score');
            $ratingSubitem->ratingCategory->update(['total_score' => $totalScore]);

            $response = [
                'message' => 'RatingSubitem created.',
                'data'    => $ratingSubitem->toArray(),
            ];

            if ($request->wantsJson()) {

                return response()->json($response);
            }

            return redirect()->back()->with('message', $response['message']);
        } catch (ValidatorException $e) {
            if ($request->wantsJson()) {
                return response()->json([
                    'error'   => true,
                    'message' => $e->getMessageBag()
                ]);
            }

            return redirect()->back()->withErrors($e->getMessageBag())->withInput();
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $ratingSubitem = $this->repository->find($id);

        if (request()->wantsJson()) {

            return response()->json([
                'data' => $ratingSubitem,
            ]);
        }

        return view('ratingSubitems.show', compact('ratingSubitem'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $ratingSubitem = $this->repository->find($id);
        $categories = RatingCategory::all()->pluck('category_name', 'id');
        return view('ratingSubitems.edit', compact('ratingSubitem', 'categories'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  RatingSubitemUpdateRequest $request
     * @param  string            $id
     *
     * @return Response
     *
     * @throws \Prettus\Validator\Exceptions\ValidatorException
     */
    public function update(RatingSubitemUpdateRequest $request, $id)
    {
        try {

            $this->validator->with($request->all())->passesOrFail(ValidatorInterface::RULE_UPDATE);

            $ratingSubitem = $this->repository->update($request->all(), $id);
            $categories = RatingCategory::all();
            foreach ($categories as $category) {
                $totalScore = $category->ratingSubitems()->sum('subitem_score');
                $category->update(['total_score' => $totalScore]);
            }
            $response = [
                'message' => 'RatingSubitem updated.',
                'data'    => $ratingSubitem->toArray(),
            ];

            if ($request->wantsJson()) {

                return response()->json($response);
            }

            return redirect()->back()->with('message', $response['message']);
        } catch (ValidatorException $e) {

            if ($request->wantsJson()) {

                return response()->json([
                    'error'   => true,
                    'message' => $e->getMessageBag()
                ]);
            }

            return redirect()->back()->withErrors($e->getMessageBag())->withInput();
        }
    }


    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $ratingSubitem = $this->repository->find($id);
        $deleted = $ratingSubitem->delete($id);
        $totalScore = $this->repository->where('category_id', $ratingSubitem->category_id)->sum('subitem_score');
        $ratingSubitem->ratingCategory->update(['total_score' => $totalScore]);
        if (request()->wantsJson()) {
            return response()->json([
                'message' => 'RatingSubitem deleted.',
                'deleted' => $deleted,
            ]);
        }

        return redirect()->back()->with('message', 'RatingSubitem deleted.');
    }

    public function getSubitemsByCategory(Request $request)
    {
        $subitems = $this->repository->where('category_id', $request->category_id)->orderBy('id')->get();
        return response()->json($subitems);
    }
}
